#!/bin/bash

# Return value
Ture=0
False=1

# Path record
src_path=`pwd`
find_path=".find_path.txt"
find_file=".find_file.txt"

# Show how to use this shell
function usage()
{
    printf "usage: bash FILE.SH \033[32m\"search name\"\033[0m \n"
    printf "Kill all grep processes command:\n"
    printf "    \033[32mps aux | grep grep | cut -c 9-15 | xargs kill -15\033[0m\n\n"
    exit $Ture
}

if [[ $# < 1 ]];then
    printf "Try 'bash [FILE.SH] --help' for more information.\n"
    exit $False
fi

# Creating a Dynamic Array
_ArrayNum=0
while [ $# -gt 0 ]
do
    _ArrayName[${_ArrayNum}]=$1
    let _ArrayNum++
    shift
done
let _ArrayNum--

case ${_ArrayName[0]} in
    -h|--help)
        usage
    ;;
    *)
        # Find all repository paths
        printf "\033[32m[INFO]\033[0m Start finding local repositories ...\n"
        find . -type d  -name .git 2>/dev/null > ${find_path}
        sed -i "s/.git//g" ${find_path} # remove .git in find_path
        # Check the number of git repositories
        if [[ `wc -l ${find_path} | awk '{print $1}'` -lt 10 ]];then
            printf "\033[33m[WARNING]\033[0m git repository is less than 10!\n"
            # Check if there is a tree directive
            dpkg -s tree > /dev/null 2>&1
            if [[ $? -ne 0 ]];then
                printf "\033[33m[WARNING]\033[0m package 'tree' is not installed!\n"
                # exit $False
            fi
            # exit $False
        fi
        # To every path grep data
        printf "\033[32m[INFO]\033[0m Start finding ${_ArrayName[0]} ...\n"
        printf "Start Search ------>\n" > ${find_file}
        for i in `cat ${find_path}`;do
            printf "\033[32m[INFO]\033[0m find \"${_ArrayName[0]}\" in $i\n"
            grep -Rn "${_ArrayName[0]}" $i >> ${find_file} &
        done
        printf "\033[32m[INFO]\033[0m End finding ${_ArrayName[0]} ...\n"

        printf "\n\033[33m[NOTE]\033[0m View Results: \n"
        printf "\033[32mcat ${find_file} | grep \"${_ArrayName[0]}\"\033[0m"
        printf "\n\033[33m[NOTE]\033[0m Delete all child processes: \n"
        printf "\033[32mps aux | grep grep | cut -c 9-15 | xargs kill -15\n\033[0m"
    ;;
esac